<!--
 * @Description: 描述
 * @Author: liym
 * @Date: 2025-05-08 20:14:38
 * @LastEditors: liym
 * @LastEditTime: 2025-05-12 15:37:50
-->
<template>
  <view class="profile-page">
    <uni-section title="个人资料" type="line"></uni-section>
    <uni-list>
      <uni-list-item title="用户名" :rightText="profile.userName" />
      <uni-list-item title="联系方式" :rightText="profile.phone" />
      <!-- <uni-list-item title="创建时间" :rightText="profile.createTime" /> -->
    </uni-list>
    <button @click="showEditModal">修改密码</button>
    <!-- 修改密码弹窗 -->
    <uni-popup ref="editModal">
      <view class="modal-content">
        <uni-forms ref="editForm" :model="passwordForm" :rules="passwordRules">
          <uni-forms-item name="oldPassword">
            <uni-easyinput type="password" v-model="passwordForm.password" placeholder="请输入密码" />
          </uni-forms-item>
          <uni-forms-item name="newPassword">
            <uni-easyinput type="password" v-model="passwordForm.passwordRepet" placeholder="请确认输入密码" />
          </uni-forms-item>
          <button type="primary" @click="submitPasswordForm">提交</button>
        </uni-forms>
      </view>
    </uni-popup>
  </view>
</template>

<script>

import { adminRedirectionMixin } from '@/common/commonMixins.js';
import { getUserByIdApi, changePasswordApi } from '@/api';
export default {
  mixins: [adminRedirectionMixin],
  data() {
    return {
      profile: {},
      passwordForm: {
        password: '',
        passwordRepet: ''
      },
      passwordRules: {
        oldPassword: { required: true, message: '请输入密码' },
        newPassword: { required: true, message: '请确定密码' }
      }
    };
  },
  mounted() {
    this.fetchProfile();
  },
  methods: {
    async fetchProfile () {
      try {
        uni.showLoading({
          title: 'loading',
          mask: true
        })
        const user = uni.getStorageSync('user')
        const res = await getUserByIdApi({ userId: user.id });
        this.profile = res.data;
      } finally {
        uni.hideLoading()
      }
    },
    showEditModal() {
      this.$refs.editModal.open();
    },
    
    async submitPasswordForm() {
      try {
        await this.$refs.editForm.validate();
        uni.showLoading({
						title: 'loading',
						mask: true
        })
        const {password, passwordRepet} = this.passwordForm
        if (password !== passwordRepet) {
          uni.showToast({ title: '两次密码输入不一致' })
          return
        }
        await changePasswordApi({ key: password })
        uni.hideLoading()
        uni.showToast({ title: '密码修改成功' });
        this.$refs.editModal.close();
      } catch (e) {
        uni.hideLoading()
        uni.showToast({ title: e.message, icon: 'none' });
      }
    }
  }
};
</script>